﻿using ApiGateway.Core;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace ApiGateway.Controllers
{
    public class GatewayController : ApiController
    {
        [HttpGet]
        public async Task<HttpResponseMessage> Execute(string system)
        {
            var request = Request;

            if (!BootStartup.RoutingTable.ContainsKey(system))
            {
                var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
                var content = new StringContent("Unknown route", Encoding.UTF8, "application/text");
                httpResponseMessage.Content = content;
                return httpResponseMessage;

                //return await base.SendAsync(request, cancellationToken);
            }

            var routeUri = BootStartup.RoutingTable[system];
            var gatewayUrl = string.Format("{0}/{1}", BootStartup.RoutingTable["ApiGateway"], system);

            var forwardUriAsString = request.RequestUri.ToString().Replace(gatewayUrl, routeUri);

            request.RequestUri = new Uri(forwardUriAsString);

            var client = new HttpClient();
            if (request.Method == HttpMethod.Get)
                request.Content = null;
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            return response;
        }
    }
}
